package com.wanghaibo.vgashow.climatecontrol;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class AutoSwingFlapHandler extends Handler {
    private static final int INTERVAL_TIME_MILLIS = 80;
    private Runnable runnable;
    private Context mContext;
    private WindView windView01;
    private WindView windView02;
    private WindView windView03;
    private WindView windView04;
    private boolean isRunning;
    private long startTime;

    public AutoSwingFlapHandler(Context context, WindView windView01,
                                WindView windView02, WindView windView03, WindView windView04) {
        this.mContext = context;
        this.windView01 = windView01;
        this.windView02 = windView02;
        this.windView03 = windView03;
        this.windView04 = windView04;
        isRunning = false;
    }

    /**
     * 时间t与windY的对应关系
     *
     * @param currentTime 当前时间（毫秒）
     * @return windY值
     */
    private int[] calculateWindXY(long currentTime) {
        int period = 10000;//运动循环周期为10秒
        long t = (currentTime % period);
        int x = 50;
        int y;
        if (t < 5000) {
            x = 50;
            y = (int) (Math.pow(t - 5000, 2) / 250000);
        } else if (t < 8000) {
            x = (int) (-t / 60 + 400 / 3);
            y = 0;
        } else {
            x = 0;
            y = (int) (t / 20 - 400);
        }
//        Log.d("TAG", "calculateWindXY: " + x + ", " + y);
        return new int[]{x, y};
    }

    public void startAutoSwingFlap() {
        if (!isRunning) {
            startTime = System.currentTimeMillis();
            runnable = () -> {
                long t = System.currentTimeMillis();
//                    Log.d("TAG", "run: " + t);
                int[] xy = calculateWindXY(t);
                int[] reverseXY = new int[]{100 - xy[0], xy[1]};
                windView01.confirmWindXY(xy);
                windView02.confirmWindXY(reverseXY);
                windView03.confirmWindXY(xy);
                windView04.confirmWindXY(reverseXY);
                //相当于定时器，每隔若干秒执行一次该线程
                AutoSwingFlapHandler.this.postDelayed(runnable, INTERVAL_TIME_MILLIS);
            };
            this.post(runnable);
            isRunning = true;
        }
    }

    public void stopAutoSwingFlap() {
        if (isRunning) {
            this.removeCallbacks(runnable);
            isRunning = false;
        }
    }
}
